﻿@page "/admin/account"
@model Moonglade.Web.Pages.Admin.LocalAccountModel
@{
    ViewBag.Title = "Manage Accounts";
    var currentUidClaim = User.Claims.FirstOrDefault(c => c.Type == "uid");
}

@section scripts{
    <script type="module">
        import * as utils from '/js/app/utils.module.js'

        var editAccountModal = new bootstrap.Modal('#editAccountModal');
        var resetPasswordModal = new bootstrap.Modal('#resetPasswordModal');

        var cid = '';

        window.deleteConfirm = function (accountId) {
            var cfm = confirm("Delete Confirmation?");
            if (cfm) {
                deleteAccount(accountId);
            }
        }

        window.deleteAccount = function (accountid) {
            callApi(`/api/localaccount/${accountid}`, 'DELETE', {},
                (resp) => {
                    document.querySelector(`#tr-${accountid}`).remove();
                });
        }

        window.resetPassword = function (accountId) {
            document.querySelector('#resetpassword-form').reset();
            resetPasswordModal.show();
            cid = accountId;
        }

        window.initCreateAccount = function () {
            document.querySelector('#new-account-form').reset();
            editAccountModal.show();
        }

        window.handleNewAccountFormSubmit = function (event) {
            event.preventDefault();

            const data = new FormData(event.target);
            const value = Object.fromEntries(data.entries());
            const newValue = utils.toMagicJson(value);

            callApi(`/api/localaccount`,
                'POST',
                newValue,
                (resp) => {
                    document.querySelector('#new-account-form').reset();
                    editAccountModal.hide();
                    window.location.reload();
                });
        }

        window.handleResetPasswordFormSubmit = function (event) {
            event.preventDefault();

            const data = new FormData(event.target);
            const value = Object.fromEntries(data.entries());

            callApi(`/api/localaccount/${cid}/password`,
                'PUT',
                value["NewPassword"],
                (resp) => {
                    document.querySelector('#resetpassword-form').reset();
                    resetPasswordModal.hide();
                    blogToast.success('Password updated.');
                    cid = '';
                });
        }

        const newAccountForm = document.querySelector('#new-account-form');
        newAccountForm.addEventListener('submit', handleNewAccountFormSubmit);

        const resetPasswordForm = document.querySelector('#resetpassword-form');
        resetPasswordForm.addEventListener('submit', handleResetPasswordFormSubmit);
    </script>
}

    <div class="admin-toolbar ps-4 pe-4 pt-2 pb-2 border-bottom mb-3 shadow-sm">
        <a class="btn btn-outline-accent" href="javascript:initCreateAccount();">
            <i class="bi-plus-lg"></i>
            @SharedLocalizer["Create"]
        </a>
    </div>

    <div class="ps-4 pe-4">
    @if (null != Model.Accounts && Model.Accounts.Any())
    {
        <table class="table table-bordered mt-3">
            <thead>
                <tr>
                    <th>@SharedLocalizer["Username"]</th>
                    <th>@SharedLocalizer["Last Login IP"]</th>
                    <th>@SharedLocalizer["Last Login Time (UTC)"]</th>
                    <th>@SharedLocalizer["Create Time (UTC)"]</th>
                    <th>@SharedLocalizer["Action"]</th>
                </tr>
            </thead>
            <tbody>
                @foreach (var item in Model.Accounts.OrderBy(p => p.Username))
                {
                    <tr id="tr-@item.Id">
                        <td>@item.Username</td>
                        <td>@(item.LastLoginIp ?? "N/A")</td>
                        <td>@(null != item.LastLoginTimeUtc ? item.LastLoginTimeUtc.ToString() : "N/A")</td>
                        <td>@item.CreateTimeUtc</td>
                        <td>
                            <a href="javascript:resetPassword('@item.Id');" class="btn btn-sm btn-outline-accent btn-updatepwd">
                                <i class="bi-key-fill"></i>
                            </a>

                            @if (null != currentUidClaim && currentUidClaim.Value != item.Id.ToString())
                            {
                                <a href="javascript:deleteConfirm('@item.Id');" class="btn btn-sm btn-outline-danger btn-delete"><i class="bi-trash"></i></a>
                            }
                        </td>
                    </tr>
                }
            </tbody>
        </table>
    }

    <p class="text-muted">Check out <a href="https://azure.microsoft.com/en-us/services/active-directory?WT.mc_id=AZ-MVP-5002809">Azure Active Directoy</a> and empower your blog to achieve more!</p>

</div>

<div class="modal fade" id="editAccountModal" tabindex="-1" role="dialog" aria-labelledby="editAccountModalLabel" aria-hidden="true">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="editAccountModalLabel">@SharedLocalizer["Account Information"]</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close">
                </button>
            </div>

            <form id="new-account-form" method="post">
                <div class="modal-body">
                    <div class="mb-2">
                        <label asp-for="ViewModel.Username"></label>
                        <input asp-for="ViewModel.Username" class="form-control" required pattern="[a-z0-9]+" minlength="2" maxlength="32" />
                        <small class="text-muted">Username must be lower case letters or numbers.</small>
                    </div>
                    <div class="mb-2">
                        <label asp-for="ViewModel.Password"></label>
                        <input asp-for="ViewModel.Password" class="form-control" required pattern="^(?=.*[a-zA-Z])(?=.*[0-9])[A-Za-z0-9._~!@@#$^&*]{8,}$" />
                        <small class="text-muted">Password must be minimum eight characters, at least one letter and one number</small>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="submit" class="btn btn-outline-accent btn-submit">@SharedLocalizer["Submit"]</button>
                    <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">@SharedLocalizer["Cancel"]</button>
                </div>
            </form>
        </div>
    </div>
</div>

<div class="modal fade" id="resetPasswordModal" tabindex="-1" role="dialog" aria-labelledby="resetPasswordModalLabel" aria-hidden="true">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="resetPasswordModalLabel">@SharedLocalizer["Reset Password"]</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close">
                </button>
            </div>

            <form id="resetpassword-form" method="post">
                <div class="modal-body">
                    <div class="mb-2">
                        <label for="NewPassword">New Password</label>
                        <input class="form-control" type="password"
                               id="NewPassword"
                               minlength="8"
                               maxlength="32"
                               name="NewPassword"
                               pattern="^(?=.*[a-zA-Z])(?=.*[0-9])[A-Za-z0-9._~!@@#$^&*]{8,}$"
                               required>
                        <span class="text-danger field-validation-valid"></span>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="submit" class="btn btn-outline-accent btn-resetpwd">@SharedLocalizer["Submit"]</button>
                    <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">@SharedLocalizer["Cancel"]</button>
                </div>
            </form>
        </div>
    </div>
</div>
